<?php

namespace App\DataFixtures;

use App\Entity\Category;
use App\Entity\Product;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;

/**
 * Class ProductFixtures
 * @package App\DataFixtures
 * 执行ProductFixtures前会先执行依赖CategoryFixtures
 */
class ProductFixtures extends Fixture implements DependentFixtureInterface
{

    public function load(ObjectManager $manager)
    {
        /** @var Category $lastCategory */
        $lastCategory = $this->getReference('lastCategory');

        $categoryRepository = $manager->getRepository(Category::class);
        for ($i = 0; $i < 100; $i++){
            $product = new Product();
            $product->setName('product#'.$i);
            $product->setPrice(mt_rand(10,10000)/100);
            // 随机绑定Category
            if (mt_rand(0,1)){
                $category =$categoryRepository->find(mt_rand($lastCategory->getId()-CategoryFixtures::BATCH_SIZE+1, $lastCategory->getId()));
                $product->setCategory($category);
            }
            $manager->persist($product);
        }
        $manager->flush();
    }

    public function getDependencies()
    {
        return [CategoryFixtures::class];
    }

}
